package com.fos.BluetoothStory.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.fos.BluetoothStory.GlobalApplication;
import com.fos.BluetoothStory.R;
import com.fos.BluetoothStory.adapter.MenuAdapter;
import com.fos.BluetoothStory.adapter.SongsListAdapter;
import com.fos.BluetoothStory.data.TFMusicState;
import com.fos.BluetoothStory.model.MusicBean;
import com.fos.BluetoothStory.service.BluetoothChatService;
import com.fos.BluetoothStory.service.PlaySongService;
import com.fos.BluetoothStory.service.PlayerStateListener;
import com.fos.BluetoothStory.util.AppConstance;
import com.fos.BluetoothStory.util.CommandUtil;
import com.fos.BluetoothStory.util.DeviceSongsCatch;
import com.fos.BluetoothStory.util.LocalSongsUtil;
import com.fos.BluetoothStory.widget.ClearableEditText;
import com.fos.BluetoothStory.widget.RecyclerViewEmptySupport;
import com.kyleduo.switchbutton.SwitchButton;

import java.util.ArrayList;

/**
 * 主页
 * @author fanxing 创建于 Oct 22, 2015
 */
public class MainActivity extends Activity implements OnCheckedChangeListener, OnItemClickListener,
	ServiceConnection{
	//Handler what
	private static final int LOADING_MUSIC = 0;
	
	// Intent request codes
	private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
	private static final int REQUEST_ENABLE_BT = 3;
	
	// Message types sent from the BluetoothChatService Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;

    // Key names received from the BluetoothChatService Handler
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";
	
	private SongsListAdapter songsListAdapter;
	private ArrayList<MusicBean> localSongs;
	private AudioManager mAudioManager;
	private PlayerStateListener playerStateListener;
	private LocalBroadcastManager lbm;
	private SwitchButton switchButton;
	private BluetoothAdapter mBtAdapter;
	private MenuAdapter menuAdapter;
	private int currentPid;
	private BluetoothChatService mChatService;
	private ProgressDialog connectingDialog;
	private ProgressDialog loadingMusicDialog;
	private Toast toast;
	private View iv_play;
	private TFMusicState mState;

	private ClearableEditText searchUI;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBtAdapter == null) {
        	showToast(getString(R.string.device_unable));
            finish();
            return;
        }
        
		mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); 
		lbm = GlobalApplication.lbm;
		
		initBlSwitch();
		
		iv_play = findViewById(R.id.iv_play);
		//选择设备进行连接
		findViewById(R.id.ib_add).setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (!mBtAdapter.isEnabled()) {
		            requestBlutooth();
		        }else{
		        	Intent serverIntent = new Intent(MainActivity.this, DeviceListActivity.class);
		        	startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
		        }
			}
		});
		
		initSearch();
		
		initMenuList();
		initRecyclerView();
		initLocalForAdapter();
		mState = TFMusicState.getInstance();

		//绑定音乐服务
		Intent servicePlay = new Intent(this, PlaySongService.class);
		bindService(servicePlay, this, Context.BIND_AUTO_CREATE);
		//绑定蓝牙服务
		Intent serviceBlue = new Intent(this, BluetoothChatService.class);
		bindService(serviceBlue, this, Context.BIND_AUTO_CREATE);
		initReceiver();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unbindService(this);
		lbm.unregisterReceiver(myReceiver);
	}

	private void initSearch() {
		searchUI = (ClearableEditText) findViewById(R.id.editText);
		searchUI.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			//action=ACTION_DOWN, keyCode=KEYCODE_ENTER
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if(actionId==EditorInfo.IME_ACTION_SEND || (event!=null && event.getKeyCode()==KeyEvent.KEYCODE_ENTER)){
					hideInput();
					
					songsListAdapter.doSearch(v.getText());
					return true;
				}
				return false;
			}

		});
		searchUI.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				songsListAdapter.doSearch(searchUI.getText());
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			
			@Override
			public void afterTextChanged(Editable s) {}
		});
	}

	private void hideInput() {
		InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		if(inputMethodManager.isActive()){
			inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}
	//toast
	private void showToast(String msg, int... duration){
		int dur = (duration==null || duration.length==0) ? Toast.LENGTH_LONG : duration[0];
		if(toast != null){
			toast.cancel();
			toast.setText(msg);
			toast.setDuration(dur);
		}else{
			toast = Toast.makeText(this, msg, dur);
		}
		toast.show();
	}
	
	//初始化广播
	private void initReceiver() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(BluetoothChatService.BCS_SONGS_UPDATE);
		filter.addAction(BluetoothChatService.BCS_STATE_CHANGE);
		filter.addAction(BluetoothChatService.BCS_WORK_UPDATE);
		filter.addAction(BluetoothChatService.BCS_STATE_PLAY_UPDATE);
		filter.addAction(BluetoothChatService.BCS_STATE_PLAY_UPDATE_DEVICE);
		filter.addAction(PlaySongService.INTENT_PLAY_STATE);
		lbm.registerReceiver(myReceiver, filter);
	}
	private BroadcastReceiver myReceiver = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			switch (action) {
				case BluetoothChatService.BCS_SONGS_UPDATE:
					showLoadingMusic();
					int pid = intent.getIntExtra(BluetoothChatService.SONGS_UPDATE_PID, -1);
					if(currentPid == pid){//更新adapter
						songsListAdapter.setDatas(DeviceSongsCatch.get(currentPid), getPlayingSong());
					}
					break;
				case BluetoothChatService.BCS_STATE_CHANGE:
					int state = intent.getIntExtra(BluetoothChatService.STATE_FLAG, BluetoothChatService.STATE_NONE);
					if(state == BluetoothChatService.STATE_CONNECTED){
						if (AppConstance.sPID==-1 && AppConstance.sPlayState != 0) {
				            mChatService.sendMessage(CommandUtil.cSetPlayMode((byte) 0x00));
				            AppConstance.sNeedState = 0;
				        }
						if(connectingDialog!=null && connectingDialog.isShowing()){
							connectingDialog.dismiss();
						}
						switchButton.setChecked(mBtAdapter.isEnabled());
						showToast(getString(R.string.tip_device_connected_succ));
					}else if(state == BluetoothChatService.STATE_LISTEN){
						if(connectingDialog!=null && connectingDialog.isShowing()){
							connectingDialog.dismiss();
							showToast(getString(R.string.tip_device_connected_fail));
						}
					}
					break;
				case BluetoothChatService.BCS_WORK_UPDATE:
					pauseLocalPlay();//停止当前播放
					iv_play.setSelected(false);
					mChatService.sendMessage(CommandUtil.queryPlayState());
					mChatService.sendMessage(CommandUtil.queryPlayMode());
					break;
				case BluetoothChatService.BCS_STATE_PLAY_UPDATE://播放按钮
					Log.e("fan", "播放按钮"+AppConstance.isPlayOrPause());
					iv_play.setSelected(AppConstance.isPlayOrPause());
					break;
				case BluetoothChatService.BCS_STATE_PLAY_UPDATE_DEVICE://音箱按钮
					Log.e("fan", "音箱按钮"+AppConstance.isPlayOrPause());
					iv_play.setSelected(AppConstance.isPlayOrPause());
					break;
				case PlaySongService.INTENT_PLAY_STATE:
					boolean isPlay = intent.getBooleanExtra(PlaySongService.STATE, false);
					if(AppConstance.sPID == -1){
						iv_play.setSelected(isPlay);
					}
					break;
				default:
					break;
			}
		}
	};

	@Override
	public void onServiceDisconnected(ComponentName name) {
	}
	
	@Override
	public void onServiceConnected(ComponentName name, IBinder service) {
		if(service instanceof BluetoothChatService.MyBinder){
			mChatService = ((BluetoothChatService.MyBinder)service).getService();
		}else if(service instanceof PlaySongService.MyBinder){
			playerStateListener = ((PlaySongService.MyBinder)service).getListener();
		}
		iv_play.setSelected(AppConstance.isPlayOrPause() || (playerStateListener!=null ? playerStateListener.isPlaying() : false));
	}
	
	public void pauseLocalPlay(){
		Intent songB = new Intent(PlaySongService.INTENT_PLAY_SONG);
		lbm.sendBroadcast(songB);
	}

	//蓝牙开关
	private void initBlSwitch() {
		switchButton = (SwitchButton)findViewById(R.id.switchButton);
		switchButton.setOnCheckedChangeListener(this);
		switchButton.setChecked(mBtAdapter.isEnabled());
	}
	/**蓝牙的开关*/
	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if (isChecked && !mBtAdapter.isEnabled()) {
			requestBlutooth();
		}else if(!isChecked){
			mBtAdapter.disable();//关闭蓝牙
		}
	}
	
	//请求打开蓝牙
	private void requestBlutooth() {
		Intent enableIntent = new Intent(
		BluetoothAdapter.ACTION_REQUEST_ENABLE);
		startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
	}

	/**菜单初始化*/
	private void initMenuList() {
		ListView listView = (ListView) findViewById(R.id.listView);
		menuAdapter = new MenuAdapter(this);
		listView.setAdapter(menuAdapter);
		listView.setOnItemClickListener(this);
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		menuAdapter.changeSelect(position);
		currentPid = position + 1;
		switch (position) {
			case 0:
			case 1:
			case 2:
			case 3://蓝牙设备音乐
				if(BluetoothChatService.STATE_CONNECTED != mChatService.getState()){
					requestBlutooth();
					initLocalForAdapter();
					menuAdapter.changeSelect(4);
					break;
				}
				if(AppConstance.sPID == currentPid)//是当前的
					break;
				
				AppConstance.sPID = currentPid;
				if(AppConstance.sPlayState != 3){
					mChatService.sendMessage(CommandUtil.cSetPlayMode((byte)0x03));
					break;
				}
				
//				mChatService.sendMessage(CommandUtil.queryPlayState());
//				mChatService.sendMessage(CommandUtil.queryPlayMode());
				
				ArrayList<MusicBean> mus = DeviceSongsCatch.get(currentPid);
				if(mus==null || mus.size()==0){
					iv_play.setSelected(false);
					mChatService.sendMessage(CommandUtil.cgetListMusic(new byte[] {
							(byte) currentPid, (byte) 0x00, (byte) 12, (byte) 0x00}));
					songsListAdapter.setDatas(null, getPlayingSong());
					showLoadingMusic();
				}else{
					songsListAdapter.setDatas(DeviceSongsCatch.get(currentPid), getPlayingSong());
				}
//				DeviceSongsCatch.clear(currentPid);
				break;
			case 4://本地音乐
				AppConstance.sPID = -1;
				if (AppConstance.sPlayState != 0) {
		            mChatService.sendMessage(CommandUtil.cSetPlayMode((byte) 0x00));
		            AppConstance.sNeedState = 0;
		        }
				initLocalForAdapter();
				iv_play.setSelected(playerStateListener==null ? false : playerStateListener.isPlaying());
				break;
		}
	}

	private void showLoadingMusic() {
		if(loadingMusicDialog==null){
			loadingMusicDialog = ProgressDialog.show(this, "", getString(R.string.tip_prepareing), true, false);
		}else if(!loadingMusicDialog.isShowing()){
			loadingMusicDialog.show();
		}
		handler.removeMessages(LOADING_MUSIC);
		handler.sendEmptyMessageDelayed(LOADING_MUSIC, 500);
	}
	
	private Handler handler = new Handler(){
		public void handleMessage(Message msg) {
			int w = msg.what;
			if(w == LOADING_MUSIC){
				loadingMusicDialog.dismiss();
			}
		};
	};

	private void initLocalForAdapter() {
		if(localSongs==null || localSongs.size()<=0){
			localSongs = LocalSongsUtil.getLocalSongsInfos(getContentResolver());
		}
		songsListAdapter.setDatas(localSongs, getPlayingSong());
	}
	
	private String getPlayingSong(){
		return playerStateListener==null ? null : playerStateListener.getSongPath();
	}

	private void initRecyclerView() {
		RecyclerViewEmptySupport mRecyclerView = (RecyclerViewEmptySupport)findViewById(R.id.recyclerView);
		LinearLayoutManager mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
		mRecyclerView.setHasFixedSize(true);
		mRecyclerView.setLayoutManager(mLayoutManager);
		songsListAdapter = new SongsListAdapter(this);
        mRecyclerView.setAdapter(songsListAdapter);
        mRecyclerView.setEmptyView(findViewById(R.id.empty_view));
//        DividerItemDecoration mDividerItemDecoration = new DividerItemDecoration(this, mLayoutManager.getOrientation());
//        mRecyclerView.addItemDecoration(mDividerItemDecoration);
	}
	
	/**播放或暂停*/
	public void onPlayOrPause(View v){
		if(AppConstance.sPlayState == 0 || AppConstance.sPlayState == -1){//本地播放
//			boolean f = mAudioManager.isBluetoothA2dpOn();
//			showToast("蓝牙音乐状态"+f);
			
			if(playerStateListener == null){
				showToast(getString(R.string.error_restart));
				return;
			}
			
			boolean isPlaying = !playerStateListener.isPlaying();
			Intent songB = new Intent(PlaySongService.INTENT_PLAY_SONG);
			if(songsListAdapter.getPlayItem() == null){//无播放中的,则播放第一首
				songsListAdapter.setSelected(0);
			}
			if(songsListAdapter.getPlayItem() != null)
				songB.putExtra(PlaySongService.BROAD_SONG, songsListAdapter.getPlayItem().url);
			lbm.sendBroadcast(songB);
			
//		if(!isPlaying && playerStateListener.isPlaying()){//设置为暂停确还在播放
			v.setSelected(isPlaying);
//		}else{
//			v.setSelected(!isPlaying);
//		}
		}else{
			mChatService.sendMessage(CommandUtil.cSetPlayOrPause(!AppConstance.isPlayOrPause()));
//			playBlueMusic();
		}
		
		hideInput();
	}
	
	public void playBlueMusic(){
		MusicBean bean = songsListAdapter.getPlayItem();
		if(bean.pid == 5){//本地的
//			if (AppConstance.sPlayState != 0) {
//				mChatService.sendMessage(CommandUtil.cSetPlayMode((byte) 0x00));
//				AppConstance.sNeedState = 0;
//			}
//			iv_play.setSelected(true);
		}else{
			mChatService.sendMessage(CommandUtil.cgetListMusic(new byte[] {
					(byte) bean.pid, (byte) 0x00, (byte) 12, (byte) 0x00}));
			
			mChatService.sendMessage(CommandUtil.cSetMusic(bean.pid, bean.id));
			TFMusicState.getInstance().setPlayMusic(bean);
		}
//		mChatService.sendMessage(CommandUtil.cSetMusic(bean.id));
		hideInput();
	}

	/**上一个*/
	public void onUpPlay(View v){
		if(AppConstance.sPlayState==0 || AppConstance.sPlayState==-1){//本地
			Intent next = new Intent(PlaySongService.INTENT_PLAY_ACTION);
			next.putExtra(PlaySongService.NAME_ACTION, PlaySongService.NAME_ACTION_UP);
			lbm.sendBroadcast(next);
		}else{
			mChatService.sendMessage(CommandUtil.cSetNext((byte)0x00));
		}
	}
	
	/**下一个*/
	public void onDownPlay(View v){
		if(AppConstance.sPlayState==0 || AppConstance.sPlayState==-1){//本地
    		Intent next = new Intent(PlaySongService.INTENT_PLAY_ACTION);
    		next.putExtra(PlaySongService.NAME_ACTION, PlaySongService.NAME_ACTION_NEXT);
    		lbm.sendBroadcast(next);
		}else{
			mChatService.sendMessage(CommandUtil.cSetNext((byte)0x01));
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
			case REQUEST_CONNECT_DEVICE_INSECURE:
	            // When DeviceListActivity returns with a device to connect
	            if (resultCode == Activity.RESULT_OK) {
	                connectDevice(data, false);
	            }
	            break;
			case REQUEST_ENABLE_BT:
	            // When the request to enable Bluetooth returns
	            if (resultCode == Activity.RESULT_OK) {
	            	Intent serverIntent = new Intent(MainActivity.this, DeviceListActivity.class);
	            	startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
	            } else {
	                showToast(getString(R.string.tip_blue_unable));
	                switchButton.setChecked(false);
	            }
	            break;
		}
	}

	//蓝牙相关//////////////////////////////////////////////
	// The Handler that gets information back from the BluetoothChatService
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
                switch (msg.arg1) {
                case BluetoothChatService.STATE_CONNECTED://蓝牙连接成功
                	//握手
                	mChatService.sendMessage(CommandUtil.cShackCommand(1));
                    break;
                case BluetoothChatService.STATE_CONNECTING://连接中
                    break;
                case BluetoothChatService.STATE_LISTEN://无连接
                case BluetoothChatService.STATE_NONE:
                    break;
                }
                break;
            case MESSAGE_WRITE://往蓝牙写数据
                break;
            case MESSAGE_READ://读蓝牙数据
                break;
            case MESSAGE_DEVICE_NAME://保存连接的蓝牙设备名称
                // save the connected device's name
                break;
            case MESSAGE_TOAST://toast 消息msg.getData().getString(TOAST)
                break;
            }
        }
    };

	/**链接设备，清除缓存数据*/
	private void connectDevice(Intent data, boolean secure) {
		DeviceSongsCatch.clearAll();
		// Get the device MAC address
		String address = data.getExtras()
				.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
		// Get the BluetoothDevice object
		BluetoothDevice device = mBtAdapter.getRemoteDevice(address);
		// Attempt to connect to the device
		mChatService.connect(device);
		
		connectingDialog = ProgressDialog.show(this, "", getString(R.string.connecting), true, true);
    }
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
//		if(AppConstance.sPlayState!=0 && AppConstance.sPlayState!=-1){
			int progress = 0;
			switch (keyCode) {
				// 音量减小
				case KeyEvent.KEYCODE_VOLUME_DOWN:
					progress = (mState.getVolume() - 1) % 16;
					progress = Math.max(0, progress);
					mChatService.sendMessage(CommandUtil.cSetVolume((byte) progress));
					mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_LOWER,  
			                AudioManager.FX_FOCUS_NAVIGATION_UP);
					return true;
					// 音量增大
				case KeyEvent.KEYCODE_VOLUME_UP:
					progress = (mState.getVolume() + 1) % 16;
					progress = Math.min(16, progress);
					mChatService.sendMessage(CommandUtil.cSetVolume((byte) progress));
					mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_RAISE,  
			                AudioManager.FX_FOCUS_NAVIGATION_UP);
					return true;
			}
//		}
		return super.onKeyDown(keyCode, event);
	}
}
